package com.flyme.module.base.provider.handler;

import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.PayMessage;
import com.egzosn.pay.common.bean.PayOutMessage;
import com.egzosn.pay.common.exception.PayErrorException;
import com.flyme.common.core.model.ResultBody;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.module.base.client.entity.SysConfig;
import com.flyme.module.base.provider.service.SysBalanceService;
import com.flyme.module.base.provider.service.SysConfigService;
import com.flyme.module.file.client.entity.SysLive;
import com.flyme.module.file.provider.service.SysCourseEnrollService;
import com.flyme.module.file.provider.service.SysLiveService;
import com.flyme.module.order.client.entity.MyPayOrder;
import com.flyme.module.order.client.entity.Order;
import com.flyme.module.order.client.entity.OrderInfo;
import com.flyme.module.order.client.entity.PayBeforeHandler;
import com.flyme.module.order.client.enums.OrderStatusEnum;
import com.flyme.module.order.client.enums.PayTypeEnum;
import com.flyme.module.order.provider.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

@Component("livePayHandler")
public class LivePayHandler implements PayBeforeHandler {

	@Autowired
	private OrderService orderService;
	@Autowired
	private SysLiveService liveService;
	@Autowired
	private SysBalanceService balanceService;
	@Autowired
	private SysConfigService configservice;
	@Autowired
	private SysCourseEnrollService courseEnrollService;

	/**
	 * 创建订单
	 */
	@Override
	public ResultBody addOrder(HttpServletRequest request, OrderInfo orderInfo) {
        Long liveId = orderInfo.getTargetId();
		Long userId = orderInfo.getUserId();
		//1.查询用户是否有该课程
		Integer isApply = courseEnrollService.isApply(liveId, userId, 2);
		if(isApply>0){
			return ResultBody.failed("您已购买过该课程，无法重复购买");
		}
		//1.查询用户是否有该课程的待支付订单
		Order order = orderService.findByUser(liveId, userId);
		if(ObjectUtils.isNotEmpty(order)){
			return ResultBody.failed("您有未支付订单，无法重复下单").setData(order.getId());
		}
		SysLive live= liveService.getById(liveId);
		if(orderInfo.getApplyType().equals(1) || orderInfo.getApplyType().equals(3)){
			orderInfo.setAmount(live.getRegFee());
		}else{
			SysConfig config = configservice.getByName("iosRatio");
			BigDecimal iosRatio = new BigDecimal(config.getConfigVal());
			BigDecimal price = live.getRegFee().multiply(iosRatio).setScale(0, BigDecimal.ROUND_UP);
			orderInfo.setAmount(price);
		}
		orderInfo.setBody(live.getLiveTitle());
		orderInfo.setOrderImg(live.getLiveImage());
		return orderService.createOrder(orderInfo);
	}

	/**
	 * 获取支付参数
	 */
	@Override
	public MyPayOrder getPayOrder(HttpServletRequest request) {
		MyPayOrder order = new MyPayOrder();
		order.setMethedType("APP");
		order.setTest(false);
		// 初始化支付记录
		// payinfoService.init(userOrder, order.getOutTradeNo(), "vip购买",
		// "vip购买", payType, "");
		return order;
	}

	/**
	 * 支付回调验证验证
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public boolean intercept(PayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {
		// 重复回调不进行处理
		String outTradeNo = payMessage.getOutTradeNo();
        Order order = orderService.findByNo(outTradeNo);
        if(!order.getOrderStatus().equals(OrderStatusEnum.unpaid)){//订单不为未支付，重复回调
        	return false;
        }
		return true;
	}

	/**
	 * 回调成功业务处理
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public PayOutMessage handle(PayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {
		String payCode = String.valueOf(payService.getPayConfigStorage().getPayType());
        Map<String, Object> message = payMessage.getPayMessage();
        //交易状态
        String trade_status = (String) message.get("trade_status");
        //上下文对象中获取账单
        //AmtApply amtApply = (AmtApply)context.get("amtApply");
        //日志存储
        //amtPaylogService.createAmtPaylogByCallBack(amtApply,  message.toString());
        if("aliPay".equals(payCode)){//支付宝
        	//交易完成
            if ("TRADE_SUCCESS".equals(trade_status) || "TRADE_FINISHED".equals(trade_status)) {//支付成功或支付完成
                //BigDecimal payAmount = new BigDecimal((String) message.get("total_fee"));
                String outTradeNo = payMessage.getOutTradeNo();
                Order order = orderService.findByNo(outTradeNo);
                order.setPayType(PayTypeEnum.Alipay);
				balanceService.pay_back(order);
                return payService.getPayOutMessage("success", "成功");
            }/* else if ("WAIT_BUYER_PAY".equals(trade_status) || "TRADE_CLOSED".equals(trade_status)) {//支付等待或支付关闭

            }*/
        }
        if("wxPay".equals(payCode)){//微信支付
        	if ("SUCCESS".equals(payMessage.getPayMessage().get("result_code"))){
                /////这里进行成功的处理
        		String outTradeNo = payMessage.getOutTradeNo();
                Order order = orderService.findByNo(outTradeNo);
                order.setPayType(PayTypeEnum.WxPay);
				balanceService.pay_back(order);
                return  payService.getPayOutMessage("SUCCESS", "OK");
            }else{
            	return payService.getPayOutMessage("FAIL", "失败");
            }
        }
        return payService.getPayOutMessage("fail", "失败");
	}

}
